// userPageB/pages/userMarket/merchantsList/merchantsList.js
const app = getApp()
const { unionAsset } = require("../../../../api/api")
const WXAPI = require("../../../../api/api")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '所有商家', // 导航栏 中间的标题
      textColor: '#2C3241', // 标题颜色
      bgColor: '#FFFFFF', // 导航栏背景颜色
      isColor: true,
    },
    loading: true,
    currentNavtab: '',
    NavtabType: [{
      id: '',
      name: '全部'
    }],
    searNav: [ //搜索类型
      {
        id: 0,
        name: '搜店铺'
      }, {
        id: 1,
        name: '搜卡名称'
      }
    ],
    searchTitle: '搜店铺',
    shopName: '',
    imgHttp: app.globalData.imgHttp,
    pageSize: 10,
    pageNum: 1,
    lnt: '', //经度
    lat: '', //纬度
    isInsurance: '', //是否参保  1 参保 2 未参保
    merchantCreditGrade: '', //商家等级
    cardList: [],
    shopList: [],
    loadingType: 0, //加载状态（0：加载中  1：加载完成没有更多）
    isPull: true, //是否刷新
    scrolldetail: 'a',
    cardName: '',
    listTotal: '',
    inoutValue: '',
    shopTypeParent:'',
    shopTypeTitle:'行业类型',//行业类型名称
    levelTitle:'商户等级',//商户等级名称
    prepaidTitle:'预付无忧',//预付无忧名称
    levelList:[
      {id: '',name:'全部'},
      {id: 'AAA级',name: 'AAA级'},
      {id: 'AA级',name: 'AA级'},
      {id: 'A级',name: 'A级'},
      {id: 'B级',name: 'B级'},
      {id: 'C级',name: 'C级'},
    ],
    prepaidList:[
      {id: '',name:'全部'},
      {id: '1',name:'参保预付无忧'},
      {id: '2',name:'未参保预付无忧'},
    ],
    endText:'已经到底啦', //加载结束文案
    tipsShow: false,//签约保险说明弹窗
    superviseTipShow: false,//资金监管弹窗
    superviseRatio: 0,//资金监管数额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var currentNavtab = options.id
    this.data.scrolldetail = 'a' + options.id
    console.log(currentNavtab)
    this.setData({
      currentNavtab: currentNavtab,
      scrolldetail: this.data.scrolldetail
    })
    this.getShowType()
    this.isGetSetting()
    // this.getCardList()
  },
  handleNavtab(e) {
    var id = e.currentTarget.dataset.id
    this.setData({
      currentNavtab: id,
      shopList: [],
      pageNum: 1,
    })
    this.getList()
  },
  //获取位置授权
  isGetSetting() {
    wx.showLoading({
      title: '定位获取中',
      mask: true,
    })
    console.log("经纬度")
    var that = this;
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        console.log("经纬度", statu['scope.userLocation'])
        if (!statu['scope.userLocation']) { //没授权
          //1、获取当前位置坐标
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res)
              app.globalData.lat = res.latitude //维度
              app.globalData.lnt = res.longitude //经度
              that.setData({
                lat: res.latitude, //维度
                lnt: res.longitude, //经度
              })
              that.getList()
            },
            fail: function (res) {
              that.getList()
            },
          })
        } else {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res)
              app.globalData.lat = res.latitude //维度
              app.globalData.lnt = res.longitude //经度
              that.setData({
                lat: res.latitude, //维度
                lnt: res.longitude, //经度
              })
              that.getList()
            }
          })
        }
      },
      fail: function (res) {
        wx.hideLoading();
      },
    })
  },
  bindPickerChange: function (e) { //店铺、卡名称选择
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      searchTitle: this.data.searNav[e.detail.value].name,
      inoutValue: '',
    })
    if (e.detail.value == 0) {
      this.data.pageNum = 1
      this.getList()
    } else {
      this.data.pageNum = 1
      this.getCardList()
    }
  },
  getShowType() { //获取行业类型
    var data = {}
    WXAPI.merchantsShowType(data, (res) => {
      console.log('列表', res)
      let list = this.data.NavtabType.concat(res.result.selectVOS)
      list.forEach((item) => {
        item.scrolldetail = 'a' + item.id
      })
      list[0].num = res.result.total
      this.setData({
        // NavtabType: this.data.NavtabType.concat(res.result)
        NavtabType: list
      })
      console.log('NavtabType', this.data.NavtabType)
    })
  },
  shopTypePicker(e) { //行业类型选择
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      shopTypeParent: this.data.NavtabType[e.detail.value].id,
    })
    if(this.data.NavtabType[e.detail.value].name=='全部'){
      this.setData({
        shopTypeTitle: '行业类型',
      })
    }else{
      this.setData({
        shopTypeTitle: this.data.NavtabType[e.detail.value].name,
      })
    }
    wx.showLoading()
    this.data.pageNum = 1
    this.getList()
  },
  levelPicker(e) { //商户等级选择
    this.setData({
      merchantCreditGrade: this.data.levelList[e.detail.value].id,
    })
    if(this.data.levelList[e.detail.value].name=='全部'){
      this.setData({
        levelTitle: '商户等级',
      })
    }else{
      this.setData({
        levelTitle: this.data.levelList[e.detail.value].name,
      })
    }
    wx.showLoading()
    this.data.pageNum = 1
    this.getList()
  },
  prepaidPicker(e) { //预付无忧类型选择
    this.setData({
      isInsurance: this.data.prepaidList[e.detail.value].id,
    })
    if(this.data.prepaidList[e.detail.value].name=='全部'){
      this.setData({
        prepaidTitle: '预付无忧',
      })
    }else{
      this.setData({
        prepaidTitle: this.data.prepaidList[e.detail.value].name,
      })
    }
    wx.showLoading()
    this.data.pageNum = 1
    this.getList()
  },
  //推荐商家列表
  getList() {
    const that = this
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true,
    // })
    var data = {
      lnt: this.data.lnt, //经度
      lat: this.data.lat, //纬度
      // shopTypeParent: this.data.currentNavtab,
      shopTypeParent: this.data.shopTypeParent,
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
      queryType: 2,
      shopName: this.data.shopName,
      isInsurance: this.data.isInsurance, //是否参保  1 参保 2 未参保
      merchantCreditGrade: this.data.merchantCreditGrade, //商家等级
    }
    setTimeout(()=>{
      wx.hideLoading()
    },6000)
    WXAPI.merchantAllListNew(data, (res) => { //原：cardAllList  新：merchantAllListNew
      console.log('列表', res)
      const {
        // size,
        total,
        records
      } = res.result
      var list = []
      var shopList = this.data.shopList
      if (res.code === 200) {
        this.data.listTotal = total
        list = records
        if (this.data.pageNum > 1) {
          this.setData({
            shopList: shopList.concat(list)
          })
        } else {
          this.setData({
            shopList: list
          })
        }
        if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
          console.log('没有分页')
          this.setData({
            loadingType: 1,
            endText:'已经到底啦'
          })
        }else{
          this.setData({
            loadingType: 0,
            endText:'加载中',
          })
        }
        if (this.data.shopList.length==0) {
          this.setData({
            endText:'暂无此类店铺',
          })
        }
        wx.hideLoading()
      }
    })
  },
  //卡列表
  getCardList() {
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true,
    // })
    const that = this
    var data = {
      cardName: this.data.cardName,
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
    }
    setTimeout(()=>{
      wx.hideLoading()
    },6000)
    WXAPI.cardListV3(data, (res) => {
      console.log('列表', res)
      const {
        // size,
        total,
        records
      } = res.result
      var list = []
      var cardList = this.data.cardList
      if (res.code === 200) {
        this.data.listTotal = total
        list = records
        if (this.data.pageNum > 1) {
          this.setData({
            cardList: cardList.concat(list)
          })
        } else {
          this.setData({
            cardList: list
          })
        }
        if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
          console.log('没有分页')
          this.setData({
            loadingType: 1,
            endText:'已经到底啦',
          })
        }else{
          this.setData({
            loadingType: 0,
            endText:'加载中',
          })
        }
        if (this.data.cardList.length==0) {
          this.setData({
            endText:'暂无数据',
          })
        }
        wx.hideLoading()
      }
    })
  },
  bindKeyInput(e) { //输入框监听
    console.log(e.detail.value)
    if (this.data.searchTitle == '搜店铺') {
      this.setData({
        cardName: '',
        shopName: e.detail.value,
      })
      wx.showLoading()
      this.data.pageNum = 1;
      this.getList();
    } else {
      this.setData({
        cardName: e.detail.value,
        shopName: '',
      })
      wx.showLoading()
      this.data.pageNum = 1;
      this.getCardList();
    }
  },
  //跳转店铺
  handleShop(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageB/pages/userStore/storesDetails/storesDetails?shopId=' + id,
    })
  },
  //跳转卡详情
  handleCard(e) {
    var id = e.currentTarget.dataset.id
    var merchantId = e.currentTarget.dataset.merchantid
    wx.navigateTo({
      url: '/userPageB/pages/userStore/cardDetail/cardDetail?assetId=' + id + '&merchantId=' + merchantId,
    })
  },
  //签约保险说明弹窗
  signedView(){
    this.setData({
      tipShow: true
    })
  },
  //资金监管弹窗
  superviseTipView(e){
    let num = e.currentTarget.dataset.superviseratio
    this.setData({
      superviseTipShow: true,
      superviseRatio: num
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setTimeout(() => {
      this.setData({
        loading: false
      })
    }, 500);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      NavtabType: [{
        id: '',
        name: '全部'
      }]
    })
    this.getShowType()
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.searchTitle == '搜店铺') {
      if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
        console.log('没有分页')
        this.setData({
          loadingType: 1,
        })
      } else {
        this.data.pageNum++; //每触底一次 page + 1;
        this.getList();
      }
    } else {
      if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
        console.log('没有分页')
        this.setData({
          loadingType: 1,
        })
      } else {
        this.data.pageNum++; //每触底一次 page + 1;
        this.getCardList();
      }
    }
    // if (this.data.isPull == true && this.data.searchTitle == '搜店铺') {
    //   var pageNum = this.data.pageNum
    //   pageNum++
    //   console.log("触底了", pageNum)
    //   this.setData({
    //     pageNum: pageNum
    //   });
    //   this.getList()
    // } else if (this.data.isPull == true && this.data.searchTitle == '搜卡名称') {
    //   var pageNum = this.data.pageNum
    //   pageNum++
    //   console.log("触底了", pageNum)
    //   this.setData({
    //     pageNum: pageNum
    //   });
    //   this.getCardList()
    // }
  },
})